﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Security.Cryptography;
using System.Web.Util;
using System.Web.Mail;
using System.Net.Mail;
using System.IO;
using System.Data;

namespace Usas.Common.Cms
{
    public class Role
    {
        public enum RedType : int
        {
            Type,
            Border,
            Article,
            Usas
        }

        public string GetTable(RedType rt)
        {
            switch (rt)
            {
                case RedType.Type:
                    return "t";
                    break;
                case RedType.Border:
                    return "b";
                    break;
                case RedType.Article:
                    return "a";
                    break;
                case RedType.Usas:
                    return "root";
                    break;
            }
            return "";
        }

        public bool CheckView(ArrayList RoleList, string CheckRole, string eid)
        {
            if (eid == System.Configuration.ConfigurationManager.AppSettings["AdminRoleEmpId"].ToString())
            {
                return true;
            }
            else
            {
                if (CheckRole.ToString().Trim() == "")
                {
                    return true;
                    //Append(LitCacheView, dt.Rows[i]["ArtTopic"].ToString(), id, dt.Rows[i]["ArtId"].ToString(), Convert.ToDateTime(dt.Rows[i]["ModfiyTime"]).ToString("yy-MM-dd"));
                }
                else
                {
                    string[] ArtViewPurview = CheckRole.ToString().Split(',');
                    for (int m = 0; m < ArtViewPurview.Length; m++)
                    {

                        if (ArtViewPurview[m].Trim() == "D0")
                        {
                            return true;
                            //Append(LitCacheView, dt.Rows[i]["ArtTopic"].ToString(), id, dt.Rows[i]["ArtId"].ToString(), Convert.ToDateTime(dt.Rows[i]["ModfiyTime"]).ToString("yy-MM-dd"));
                            //break;
                        }
                        for (int n = 0; n < RoleList.Count; n++)
                        {
                            if (ArtViewPurview[m].Trim() == RoleList[n].ToString().Trim())
                            {
                                return true;
                                //Append(LitCacheView, dt.Rows[i]["ArtTopic"].ToString(), id, dt.Rows[i]["ArtId"].ToString(), Convert.ToDateTime(dt.Rows[i]["ModfiyTime"]).ToString("yy-MM-dd"));
                                //flag = true;
                                //break;
                            }
                        }
                    }
                    return false;
                }
            }
        }


        public bool CheckEdit(ArrayList RoleList, string CheckRole, string eid)
        {
            if (eid == System.Configuration.ConfigurationManager.AppSettings["AdminRoleEmpId"].ToString())
            {
                return true;
            }
            else
            {
                if (CheckRole.ToString().Trim() == "")
                {
                    return false;
                    //Append(LitCacheView, dt.Rows[i]["ArtTopic"].ToString(), id, dt.Rows[i]["ArtId"].ToString(), Convert.ToDateTime(dt.Rows[i]["ModfiyTime"]).ToString("yy-MM-dd"));
                }
                else
                {
                    string[] ArtViewPurview = CheckRole.ToString().Split(',');
                    for (int m = 0; m < ArtViewPurview.Length; m++)
                    {

                        if (ArtViewPurview[m].Trim() == "D0")
                        {
                            return true;
                            //Append(LitCacheView, dt.Rows[i]["ArtTopic"].ToString(), id, dt.Rows[i]["ArtId"].ToString(), Convert.ToDateTime(dt.Rows[i]["ModfiyTime"]).ToString("yy-MM-dd"));
                            //break;
                        }
                        for (int n = 0; n < RoleList.Count; n++)
                        {
                            if (ArtViewPurview[m].Trim() == RoleList[n].ToString().Trim())
                            {
                                return true;
                                //Append(LitCacheView, dt.Rows[i]["ArtTopic"].ToString(), id, dt.Rows[i]["ArtId"].ToString(), Convert.ToDateTime(dt.Rows[i]["ModfiyTime"]).ToString("yy-MM-dd"));
                                //flag = true;
                                //break;
                            }
                        }
                    }
                    return false;
                }
            }
        }


        public bool CheckRole(ArrayList RoleList, string role, string eid, bool IsView)
        {
            if (eid == System.Configuration.ConfigurationManager.AppSettings["AdminRoleEmpId"].ToString())
            {
                return true;
            }
            else
            {
                if (IsView)
                {
                    if (role.ToString().Trim() == "")
                    {
                        return true;
                    }
                    else if (role.ToString().Trim() == "D0")
                    {
                        return true;
                    }
                    else
                    {
                        string[] rol = role.Split(',');
                        for (int i = 0; i < RoleList.Count; i++)
                        {
                            for (int j = 0; j < rol.Length; j++)
                            {
                                if (rol[j].ToString() == RoleList[i].ToString())
                                {
                                    return true;
                                }
                            }

                        }
                    }
                }
                else
                {
                    if (role.ToString().Trim() == "")
                    {
                        return false;
                    }
                    else if (role.ToString().Trim() == "D0")
                    {
                        return true;
                    }
                    else
                    {
                        string[] rol = role.Split(',');
                        for (int i = 0; i < RoleList.Count; i++)
                        {
                            for (int j = 0; j < rol.Length; j++)
                            {
                                if (rol[j].ToString() == RoleList[i].ToString())
                                {
                                    return true;
                                }
                            }

                        }
                    }
                }
            }
            return false;
        }


        public string GetMd5Str(string ConvertString)
        {
            Usas.Common.Cms.CurrentInfo cinfo = new CurrentInfo();

            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString + cinfo.GetEmpId())), 4, 8);
            t2 = t2.Replace("-", "");
            return t2;
        }


        /**/
        /// <summary>
        /// MD5　32位加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string GetMd5Str32(string str)
        {
            string cl = str;
            string pwd = "";
            MD5 md5 = MD5.Create();
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
            for (int i = 0; i < s.Length; i++)
            {
                pwd = pwd + s[i].ToString("X");
            }
            return pwd;
        }






        public bool SendMail(ArrayList ToEmailList, string From, string Pwd, string Subject, string Body, int port, string smtp, bool IsSSL)
        {
            try
            {
                System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
                for (int i = 0; i < ToEmailList.Count; i++)
                {
                    msg.To.Add(ToEmailList[i].ToString());
                }

                msg.From = new MailAddress(From, "Hyperion 内容管理员", System.Text.Encoding.UTF8);
                /* 上面3个参数分别是发件人地址（可以随便写），发件人姓名，编码*/
                msg.Subject = Subject;
                msg.SubjectEncoding = System.Text.Encoding.UTF8;
                msg.Body = Body;
                msg.BodyEncoding = System.Text.Encoding.UTF8;
                msg.IsBodyHtml = true;//是否是HTML邮件 
                msg.Priority = System.Net.Mail.MailPriority.High;//邮件优先级 
                SmtpClient client = new SmtpClient();
                client.Credentials = new System.Net.NetworkCredential(From, Pwd);

                client.Port = port;
                client.Host = smtp;
                client.EnableSsl = IsSSL;//经过ssl加密 
                //object userState = msg;
                client.Send(msg);

                return true;

            }
            catch
            {
                return false;
            }

        }


        public bool CheckRoleCurrent(ArrayList RoleList, string eid, RedType rt, string id, int IsEdit)
        {

            try
            {
                if (eid == System.Configuration.ConfigurationManager.AppSettings["AdminRoleEmpId"].ToString())
                {
                    return true;
                }
                Usas.BLL.Cms.cms_purview_setting stg = new Usas.BLL.Cms.cms_purview_setting();
                string p_where = "(1=0";
                for (int n = 0; n < RoleList.Count; n++)
                {
                    p_where += " or p_value='" + RoleList[n] + "'";
                }
                p_where += " or p_value='D0')";

                if (stg.GetList(p_where + " and p_table='" + GetTable(rt) + "' and p_pid=" + id + " and p_type=" + IsEdit).Tables[0].Rows.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        public DataTable GetRoleCurrent(int id, RedType rt, int isedit)
        {
            Usas.BLL.Cms.cms_purview_setting stg = new Usas.BLL.Cms.cms_purview_setting();

            string p_where = "p_type=" + isedit + " and p_table='" + GetTable(rt) + "' and p_pid=" + id;
            return stg.GetList(p_where).Tables[0];
        }

        public ArrayList GetFatherRoleInit(RedType rt, string pid, int IsEdit, ArrayList arr)
        {
            Usas.BLL.Cms.cms_purview_setting cps = new Usas.BLL.Cms.cms_purview_setting();
            Usas.BLL.Cms.cmsArticle ar = new Usas.BLL.Cms.cmsArticle();
            Usas.BLL.Cms.cmsBorder bo = new Usas.BLL.Cms.cmsBorder();
            Usas.BLL.Cms.cmsType tp = new Usas.BLL.Cms.cmsType();
            Usas.Model.Cms.cmsArticle arm = new Usas.Model.Cms.cmsArticle();
            Usas.Model.Cms.cmsBorder bom = new Usas.Model.Cms.cmsBorder();
            Usas.Model.Cms.cmsType tpm = new Usas.Model.Cms.cmsType();
            DataTable dt = null;

            switch (rt)
            {
                case RedType.Type:
                    tpm = tp.GetModel(Convert.ToInt32(pid));
                    dt = cps.GetList("p_type=" + IsEdit + " and p_table='a' and p_pid=" + pid).Tables[0];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        arr.Add(dt.Rows[i]["p_value"].ToString());
                    }
                    return arr;
                    break;
                case RedType.Border:
                    bom = bo.GetModel(Convert.ToInt32(pid));

                    dt = cps.GetList("p_type=" + IsEdit + " and p_table='b' and p_pid=" + pid).Tables[0];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        arr.Add(dt.Rows[i]["p_value"].ToString());
                    }
                    return GetFatherRoleInit(RedType.Type, bom.TypeId.ToString(), IsEdit, arr);
                    break;
                case RedType.Article:
                    arm = ar.GetModel(Convert.ToInt32(pid));

                    dt = cps.GetList("p_type=" + IsEdit + " and p_table='a' and p_pid=" + pid).Tables[0];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        arr.Add(dt.Rows[i]["p_value"].ToString());
                    }
                    if (arm.ParentArtId == 0)
                    {
                        return GetFatherRoleInit(RedType.Border, arm.BorderId.ToString(), IsEdit, arr);
                    }
                    else
                    {
                        return GetFatherRoleInit(RedType.Article, arm.ParentArtId.ToString(), IsEdit, arr);
                    }
                    break;
            }
            return null;

        }

        public string GetFatherRole(ArrayList arr)
        {
            if (arr != null)
            {
                string back = "";
                for (int i = 0; i < arr.Count; i++)
                {
                    back += arr[i].ToString() + ",";
                }

                if (back.Length > 0)
                {
                    return back.Substring(0, back.Length - 1);
                }
                else
                {
                    return "";
                }
            }
            else
            {
                return "";
            }
        }

        public string GetSelfSettingRole()
        {
            Usas.Common.Cms.CurrentInfo cinfo = new CurrentInfo();
            if (cinfo.GetSuperAdminGroup())
            {
                return "1=1";
            }

            StringBuilder sbr = new StringBuilder();
            if (cinfo.GetDepartmentId() != null)
            {
                sbr.Append(" '" + cinfo.GetDepartmentId() + "' like p_value + '%' or ");
            }

            if (cinfo.GetEmpId() != null)
            {
                sbr.Append(" p_value='" + cinfo.GetEmpId() + "' or ");
            }

            if (cinfo.GetEmpRole() != null)
            {
                for (int i = 0; i < cinfo.GetEmpRole().Count; i++)
                {
                    sbr.Append("p_value='" + cinfo.GetEmpRole()[i] + "' or ");
                }
            }

            sbr.Append(" p_value='D0' ");

            if (sbr.Length > 0)
            {
                return "( " + sbr.ToString() + " )";
            }
            else
            {
                return "1=0";
            }
        }

        public string[] GetFatherDir(RedType rt, int pid, bool IsEdit)
        {
            Usas.Common.Cms.CurrentInfo cinfo = new CurrentInfo();
            if (cinfo.GetSuperAdminGroup())
            {
                return new string[] { "root", "-1" };
            }
            else
            {
                string[] back = GetDir(GetTable(rt), pid, "", -1, "", IsEdit ? 1 : 0);

                if (back[0] == "" && back[1] == "-1")
                {
                    return null;
                }
                else
                {
                    return back;
                }
            }

        }

        private string[] GetDir(string table, int pid, string hastable, int hasid, string hasname, int IsEdit)
        {
            Usas.BLL.Cms.cmsArticle ar = new Usas.BLL.Cms.cmsArticle();
            Usas.BLL.Cms.cmsBorder bo = new Usas.BLL.Cms.cmsBorder();
            Usas.BLL.Cms.cmsType tp = new Usas.BLL.Cms.cmsType();
            Usas.BLL.Cms.cms_purview_setting cps = new Usas.BLL.Cms.cms_purview_setting();
            Usas.Model.Cms.cmsArticle arm = new Usas.Model.Cms.cmsArticle();
            Usas.Model.Cms.cmsBorder bom = new Usas.Model.Cms.cmsBorder();
            Usas.Model.Cms.cmsType tpm = new Usas.Model.Cms.cmsType();
            DataSet ds = null;
            switch (table)
            {
                case "a":
                    arm = ar.GetModel(pid);
                    ds = cps.GetList(GetSelfSettingRole() + " and p_table='a' and p_pid=" +
                        arm.ArtId + " and p_type=" + IsEdit);
                    if (ds != null)
                    {
                        hasid = ds.Tables[0].Rows.Count > 0 ? Convert.ToInt32(arm.ArtId) : hasid;
                        hastable = hasid == arm.ArtId ? "a" : hastable;
                        hasname = hasid == arm.ArtId ? arm.ArtTopic : hasname;
                    }

                    if (arm.ParentArtId != 0)
                    {
                        table = "a";
                        pid = Convert.ToInt32(arm.ParentArtId);
                    }
                    else
                    {
                        table = "b";
                        pid = Convert.ToInt32(arm.BorderId);
                    }
                    return GetDir(table, pid, hastable, hasid, hasname, IsEdit);
                    break;
                case "b":
                    bom = bo.GetModel(pid);
                    ds = cps.GetList(GetSelfSettingRole() + " and p_table='b' and p_pid=" +
                        bom.BorderId + " and p_type=" + IsEdit);
                    if (ds != null)
                    {
                        hasid = ds.Tables[0].Rows.Count > 0 ? Convert.ToInt32(bom.BorderId) : hasid;
                        hastable = hasid == bom.BorderId ? "b" : hastable;
                        hasname = hasid == bom.BorderId ? bom.BorderName : hasname;
                    }

                    table = "t";
                    pid = bom.TypeId;
                    return GetDir(table, pid, hastable, hasid, hasname, IsEdit);
                    break;
                case "t":
                    tpm = tp.GetModel(pid);
                    ds = cps.GetList(GetSelfSettingRole() + " and p_table='t' and p_pid=" +
                        tpm.TypeId + " and p_type=" + IsEdit);
                    if (ds != null)
                    {
                        hasid = ds.Tables[0].Rows.Count > 0 ? Convert.ToInt32(tpm.TypeId) : hasid;
                        hastable = hasid == tpm.TypeId ? "t" : hastable;
                        hasname = hasid == tpm.TypeId ? tpm.TypeName : hasname;
                    }

                    table = "r";
                    pid = -1;
                    return GetDir(table, pid, hastable, hasid, hasname, IsEdit);
                    break;
                case "r":
                    return new string[] { hastable, hasid.ToString(), hasname };
                    break;
            }

            return null;
        }
    }

}
